package com.cnap.multiclouldmgmt.service.impl;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import com.alibaba.fastjson.JSONObject;
import com.cnap.multiclouldmgmt.config.LogSysConfig;
import com.cnap.multiclouldmgmt.model.CommonResult;
import com.cnap.multiclouldmgmt.model.log.OperationLog;
import com.cnap.multiclouldmgmt.service.OperationLogService;
import com.cnap.multiclouldmgmt.util.JsonUtil;
import com.cnap.multiclouldmgmt.util.TokenUtils;
import com.fasterxml.jackson.core.type.TypeReference;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.stereotype.Service;

import java.util.Objects;

/**
 * 操作日志服务实现类
 *
 * @author xc
 **/
@Service
public class OperationLogServiceImpl implements OperationLogService {
    private static final Logger LOGGER = LoggerFactory.getLogger(OperationLogServiceImpl.class);
    private static final String SAVE_LOG_PATH = "/monitor/statistic/log/save";

    private final LogSysConfig logSysConfig;

    @Autowired
    public OperationLogServiceImpl(LogSysConfig logSysConfig) {
        this.logSysConfig = logSysConfig;
    }

    /**
     *
     * @param operationLog 操作日志
     * @return
     */
    @Override
    public boolean saveOperationLog(OperationLog operationLog) {
        String url = logSysConfig.getUrl() + SAVE_LOG_PATH;
        HttpResponse response = null;
        try {
            response = HttpRequest.post(url).header(HttpHeaders.AUTHORIZATION, TokenUtils.getTOKEN())
                    .body(JsonUtil.objectToJsonStr(operationLog)).execute();
        }catch (Exception e){
            LOGGER.error("saveOperationLog HttpRequest fail",e);
        }
        if ((response != null)&&(!response.isOk())) {
            LOGGER.error("can't save operation log, log={}", operationLog);
            return false;
        }
        String body = null;
        if (response == null){
            CommonResult<String> tmpResult = new CommonResult<>();
            tmpResult.setCode(200);
            body = JSONObject.toJSONString(tmpResult);
        }else {
            body = response.body();
        }
        CommonResult<String> result = JsonUtil.jsonStrToObject(body, new TypeReference<CommonResult<String>>() {
        });
        if (Objects.nonNull(result) && 200 != result.getCode()) {
            if (response != null) {
                String res = response.body();
                LOGGER.error("operation log system save operation log error, log={}, response={}", operationLog, res);
                return false;
            }
        }
        return true;
    }

    /**
     *
     * @param operationType 操作类型
     * @param message 信息
     * @return
     */
    @Override
    public boolean saveOperationLog(String operationType, String message) {

        try {
            OperationLog operationLog = new OperationLog();
            operationLog.setOperationType(operationType);
            operationLog.setMessage(message);
            operationLog.setUserName(TokenUtils.getUserName());

            return saveOperationLog(operationLog);
        }catch (Exception e){
            LOGGER.error("saveOperationLog fail",e);
        }

        return false;
    }
}
